﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Menu;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.Menu
{
    public class AddMenuHandler : IRequestHandler<AddMenuCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public AddMenuHandler(IBaseRepository<MenuModel> menuRepo,IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(AddMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var menu = menuRepo.GetAll().Where(x => x.MenuName == request.MenuName && x.IsDelete == false && x.Pid == request.Pid).FirstOrDefault();
            if (menu!=null)
            {
                res.Code = ApiEnum.Error;
                res.Msg = "同一级菜单下不允许名称重复";
                return Task.FromResult(res);
            }

            var model=mapper.Map<MenuModel>(request);
            model.CreateName = "张三";
            model.CreateTime= DateTime.Now;
            var r = menuRepo.Add(model);
            if (r>0)
            {
                res.Msg = "添加成功";
                res.Code = ApiEnum.Success;
                res.Data= r;
            }
            else
            {
                res.Msg = "添加失败";
                res.Code = ApiEnum.Error;
                res.Data = r;
            }
            return Task.FromResult(res);
        }
    }
}
